/**
 * 
 */
package com.auction.job.core.schedule;

import com.auction.job.core.service.MemberService;
import com.auction.job.domain.config.SystemConfig;
import com.auction.job.domain.util.Constant;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yisu.auction.ewf.common.spring.SpringContext;
import com.yisu.auction.ewf.common.web.HttpWebClient;
import com.yisu.auction.ewf.entity.Member;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.HashMap;
import java.util.Map;

public class AutoPurchaseJob extends BaseJob {
	private String prizeId;

	public void setPrizeId(String prizeId) {
		this.prizeId = prizeId;
	}

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		MemberService memberService = SpringContext.getBean("memberService");
		SystemConfig systemConfig = SpringContext.getBean("systemConfig");
		Member member = memberService.selectOne();
		if(member != null) {
			Map<String, String> params = new HashMap<>();
			params.put("memberId", String.valueOf(member.getId()));
			params.put("prizeId", prizeId);
			params.put("buyCount", "1");
			params.put("auctionType", "1");//正常拍
			sleep();
			String result = HttpWebClient.post(systemConfig.getCreateOrderUrl(), params);
			LOG.info("purchase response for prize[{}]: {}", prizeId, result);

			JsonObject jsonObject= new JsonParser().parse(result).getAsJsonObject();
			int errorCode = jsonObject.get("errorCode").getAsInt();
			switch (errorCode) {
				case Constant.PURCHASE_SUCCESS:
					LOG.info("successfully purchase for prize[{}]", prizeId);
					break;
				case Constant.WILL_OPEN_PRIZE:
					LOG.info("successfully purchase for prize[{}] and will open prize.", prizeId);
					postOpenRequest(systemConfig, prizeId, jsonObject.get("data").getAsString());
					break;
				case Constant.PRIZE_END:
					QuartzManager.removePurchaseJob(prizeId);
					LOG.warn("Manually stop the prize[{}]", prizeId);
					break;
				default:
					LOG.error("failed to purchase for prize[{}], error code[{}], error message[{}]",
							new String[]{prizeId, String.valueOf(errorCode), jsonObject.get("errorMessage").getAsString()});
					break;
			}
		} else {
			LOG.warn("has no virtual user!");
		}
	}


	private void postOpenRequest(SystemConfig systemConfig, String prizeId, String lastPurchaseTime) {
		Map<String, String> params = new HashMap<>();
		params.put("prizeId", prizeId);
		params.put("lastPurchaseTime", lastPurchaseTime);
		String result = HttpWebClient.post(systemConfig.getAddOpenUrl(), params);
		LOG.info("add open prize job, response for prize[{}]: {}", prizeId, result);
	}

}
